package com.youlian.cloud.gateway.filter;

import com.dianping.cat.Cat;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.youlian.cloud.log.utils.CatMsgConstants;
import com.youlian.cloud.log.utils.CatMsgContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

/**
 * Cat消息日志构建
 * @author : liukx
 * @create : 2018/8/15 14:53
 * @email  : liukx@elab-plus.com
 */
@Component
public class CatRouteFilter extends ZuulFilter {

    private static Logger logger = LoggerFactory.getLogger(CatRouteFilter.class);

    @Override
    public Object run() {
        try {
            RequestContext ctx = RequestContext.getCurrentContext();
            CatMsgContext context = new CatMsgContext();
            Cat.logRemoteCallClient(context);
            ctx.addZuulRequestHeader(Cat.Context.PARENT, context.getProperty(Cat.Context.PARENT));
            ctx.addZuulRequestHeader(Cat.Context.ROOT, context.getProperty(Cat.Context.ROOT));
            ctx.addZuulRequestHeader(Cat.Context.CHILD, context.getProperty(Cat.Context.CHILD));
            ctx.addZuulRequestHeader(CatMsgConstants.APPLICATION_KEY, Cat.getManager().getDomain());
        } catch (Throwable throwable) {
            logger.error("CatRouteFilter fail", throwable);
        }
        logger.info(" CatRouteFilter Invoke OK ");
        return null;
    }

    @Override
    public boolean shouldFilter() {
        // 是否执行该过滤器，此处为true，说明需要过滤
        return true;
    }

    @Override
    public int filterOrder() {
        // 优先级为0，数字越大，优先级越低
        return 0;
    }

    @Override
    public String filterType() {
        // 路由过滤器
        return FilterConstants.PRE_TYPE;
    }
}
